﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Data;

namespace Attendance
{
    class HttpServer
    {
        public string Login(string userName, string password)   //Login and get TeacherID
        {
            Uri getTeacherID = new Uri(@"http://signals.hyit.edu.cn:8080/attendance/loginServlet?username=" + userName + "&password=" + password);
            WebRequest wrq = WebRequest.Create(getTeacherID);
            HttpWebResponse hwr = (HttpWebResponse)wrq.GetResponse();
            Stream stream = hwr.GetResponseStream();
            StreamReader sr=new StreamReader(stream);
            string teacherID = sr.ReadLine();
            return teacherID;
        }

        public MemoryStream GetSubject(string teacherID)    //get Subject XML Data
        {
            Uri getSubject = new Uri(@"http://signals.hyit.edu.cn:8080/attendance/downloadSubject?teacherid=" + teacherID);
            WebRequest wrq = WebRequest.Create(getSubject);
            HttpWebResponse hwr = (HttpWebResponse)wrq.GetResponse();
            Stream stream = hwr.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string strSubject;
            XmlDocument xml = new XmlDocument();
            XmlElement root = xml.CreateElement("Subject");
            xml.AppendChild(root);
            while ((strSubject = sr.ReadLine()) != null)
            {
                XmlNode subjectInfo = xml.CreateElement("SubjectInfo");
                string[] infoSubject = strSubject.Split(',');
                XmlElement attrSubjectID = xml.CreateElement("ID");
                XmlText txtSubjectID = xml.CreateTextNode(infoSubject[0]);
                XmlElement attrSubjectName = xml.CreateElement("Name");
                XmlText txtSubjectName = xml.CreateTextNode(infoSubject[1]);
                subjectInfo.AppendChild(attrSubjectID);
                subjectInfo.LastChild.AppendChild(txtSubjectID);
                subjectInfo.AppendChild(attrSubjectName);
                subjectInfo.LastChild.AppendChild(txtSubjectName);
                xml.FirstChild.AppendChild(subjectInfo);
            }
            MemoryStream streamSubject = new MemoryStream();
            xml.Save(streamSubject);
            streamSubject.Seek(0, SeekOrigin.Begin);
            return streamSubject;
        }

        public MemoryStream GetClass(string teacherID, int subjectID)    //get Class XML data
        {
            //string time1 = DateTime.Now.Millisecond.ToString();
            Uri getClass = new Uri(@"http://signals.hyit.edu.cn:8080/attendance/downloadGroup?teacherid=" + teacherID + "&subjectid=" + subjectID);
            WebRequest wrq = WebRequest.Create(getClass);
            HttpWebResponse hwr = (HttpWebResponse)wrq.GetResponse();
            Stream stream = hwr.GetResponseStream();
            //string time2 = DateTime.Now.Millisecond.ToString();
            StreamReader sr = new StreamReader(stream);
            string strClass;
            //string time3 = DateTime.Now.Millisecond.ToString();
            XmlDocument xml = new XmlDocument();
            XmlElement root = xml.CreateElement("Class");
            xml.AppendChild(root);
            while ((strClass = sr.ReadLine()) != null)
            {
                XmlNode classInfo = xml.CreateElement("ClassInfo");
                string[] infoClass = strClass.Split(',');
                XmlElement attrClassID = xml.CreateElement("ID");
                XmlText txtClassID = xml.CreateTextNode(infoClass[0]);
                XmlElement attrClassName = xml.CreateElement("Name");
                XmlText txtClassName = xml.CreateTextNode(infoClass[1]);
                classInfo.AppendChild(attrClassID);
                classInfo.LastChild.AppendChild(txtClassID);
                classInfo.AppendChild(attrClassName);
                classInfo.LastChild.AppendChild(txtClassName);
                xml.FirstChild.AppendChild(classInfo);
            }
            MemoryStream streamClass = new MemoryStream();
            xml.Save(streamClass);
            streamClass.Seek(0, SeekOrigin.Begin);
            //string time4 = DateTime.Now.Millisecond.ToString();
            //System.Windows.Forms.MessageBox.Show(time1 + "\n" + time2 + "\n" + time3 + "\n" + time4 + "\n");
            return streamClass;
        }

        public MemoryStream GetStudent(int groupID)  //get Student XML Data
        {
            Uri getStudent = new Uri(@"http://signals.hyit.edu.cn:8080/attendance/downloadStudent?groupid=" + groupID);
            WebRequest wrq = WebRequest.Create(getStudent);
            HttpWebResponse hwr = (HttpWebResponse)wrq.GetResponse();
            Stream stream = hwr.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string strStudent;
            XmlDocument xml = new XmlDocument();
            XmlElement root = xml.CreateElement("Class");
            xml.AppendChild(root);
            while ((strStudent = sr.ReadLine()) != null)
            {
                XmlNode studentInfo = xml.CreateElement("StudentInfo");
                string[] infoStudent = strStudent.Split(',');
                XmlElement attrStudentID = xml.CreateElement("ID");
                attrStudentID.InnerText = infoStudent[0];
                XmlElement attrStudentName = xml.CreateElement("Name");
                attrStudentName.InnerText = infoStudent[1];
                studentInfo.AppendChild(attrStudentID);
                studentInfo.AppendChild(attrStudentName);
                xml.FirstChild.AppendChild(studentInfo);
            }
            MemoryStream streamStudent = new MemoryStream();
            xml.Save(streamStudent);
            streamStudent.Seek(0, SeekOrigin.Begin);
            return streamStudent;

        }
        /*
        * 
        * 
        * 
        * 
        */
        public bool chkLogin(string account,string password,DataSet teacher,DataSet subject)//登陆并获取教师课程信息
        {
            WebRequest reqLogin = WebRequest.Create("http://signals.hyit.edu.cn:8080/attendanceV3/querySubjectClient?account=" + account + "&password=" + password);
            reqLogin.ContentType = "multipart/form-data";
            HttpWebResponse resLogin = (HttpWebResponse)reqLogin.GetResponse();
            Stream stream = resLogin.GetResponseStream();
            XmlDocument xml = new XmlDocument();

            try
            {
                xml.Load(stream);
            }
            catch (XmlException) { throw new Exception("用户名或密码错误，请重新输入"); }

            MemoryStream tmpStream = new MemoryStream();
            xml.Save(tmpStream);
            tmpStream.Seek(0, SeekOrigin.Begin);

            DataSet ds = new DataSet();
            ds.ReadXml(tmpStream);
            teacher.Tables.Add(ds.Tables["teacher"].Copy());

            try
            {
                XmlDocument xmlSub = new XmlDocument();
                XmlNode root = xmlSub.CreateElement("info");
                xmlSub.AppendChild(root);
                XmlNodeList listSubject = xml.SelectNodes("/info/list/subject");//获取xml中课程数据
                foreach (XmlNode node in listSubject)
                    xmlSub.FirstChild.AppendChild(xmlSub.ImportNode(node, true));
                tmpStream = new MemoryStream();
                xmlSub.Save(tmpStream);
                tmpStream.Seek(0, SeekOrigin.Begin);
                subject.ReadXml(tmpStream);
            }
            catch (Exception e) { throw new Exception(e.Message); }
            return true;
        }

        public bool GetSession(string teacherNumber,string subjectNumber,DataSet dsSession) 
        {
            WebRequest reqSession = WebRequest.Create("http://signals.hyit.edu.cn:8080/attendanceV3/querySessionClient?teacherNumber=" + teacherNumber + "&subjectNumber=" + subjectNumber);
            HttpWebResponse resSession = (HttpWebResponse)reqSession.GetResponse();
            Stream stream = resSession.GetResponseStream();
            XmlDocument xml = new XmlDocument();

            try
            {
                xml.Load(stream);
            }
            catch (XmlException) {  }

            MemoryStream tmpStream = new MemoryStream();
            xml.Save(tmpStream);
            tmpStream.Seek(0, SeekOrigin.Begin);

            DataSet ds = new DataSet();
            ds.ReadXml(tmpStream);
            dsSession.Tables.Add(ds.Tables["session"].Copy());

            return true;
        }

        public bool GetCron(string teacherNumber, string sessionNumber, DataSet cron, DataSet lesson, DataSet student)//登陆并获取教师课程信息
        {
            student.Reset();
            WebRequest reqCron = WebRequest.Create("http://signals.hyit.edu.cn:8080/attendanceV3/queryCronClient?teacherNumber=" + teacherNumber + "&sessionNumber=" + sessionNumber);
            reqCron.ContentType = "multipart/form-data";
            HttpWebResponse resCron = (HttpWebResponse)reqCron.GetResponse();
            Stream stream = resCron.GetResponseStream();
            XmlDocument xml = new XmlDocument();

            try
            {
                xml.Load(stream);
            }
            catch (XmlException ex) { throw new Exception("该课程没有签到计划"); }

            MemoryStream tmpStream = new MemoryStream();
            xml.Save(tmpStream);
            tmpStream.Seek(0, SeekOrigin.Begin);

            DataSet ds = new DataSet();
            ds.ReadXml(tmpStream);
            cron.Tables.Add(ds.Tables["cron"].Copy());
            lesson.Tables.Add(ds.Tables["lesson"].Copy());

            try
            {
                XmlDocument xmlSub = new XmlDocument();
                XmlNode root = xmlSub.CreateElement("info");
                xmlSub.AppendChild(root);
                XmlNodeList listSubject = xml.SelectNodes("/info/list/student");//获取xml中课程数据
                foreach (XmlNode node in listSubject)
                    xmlSub.FirstChild.AppendChild(xmlSub.ImportNode(node, true));
                tmpStream = new MemoryStream();
                xmlSub.Save(tmpStream);
                tmpStream.Seek(0, SeekOrigin.Begin);
                student.ReadXml(tmpStream);
            }
            catch (Exception e) { throw new Exception(e.Message); }
            return true;
        }

        public string Upload(string teacherId,string cronId,string exeTime,DataTable dtChkStu)
        {
            WebRequest reqUp = WebRequest.Create(new Uri("http://signals.hyit.edu.cn:8080/attendanceV3/postCheckData"));
            reqUp.Method = "POST";
            reqUp.ContentType = "application/x-www-form-urlencoded";
            string strTeacher = "teacherNumber=" + teacherId + "&cronNumber=" + cronId + "&executeTime=" + exeTime;
            string paramData = "" + strTeacher;
            foreach (DataRow dr in dtChkStu.Rows)
            {
                paramData += "&studentNumber=" + dr["stuID"] + "&cardMac=" + dr["mac"] + "&absent=" + dr["absent"] + "&date=" + dr["date"] + "&time=" + dr["time"];
            }

            byte[] byteArray = Encoding.UTF8.GetBytes(paramData);
            reqUp.ContentLength = byteArray.Length;
            Stream newStream = reqUp.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();


            HttpWebResponse response = (HttpWebResponse)reqUp.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
            //ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            newStream.Close();

            return paramData;
        }
    }
}
